package websocket;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.CharBuffer;
import java.util.Arrays;

import org.apache.catalina.websocket.MessageInbound;
import org.apache.catalina.websocket.WsOutbound;

public class ChatConnection extends MessageInbound {
	
	String group;
	
	public ChatConnection(String group) {
		this.group = group;
	}
	
	@Override
	protected void onOpen(WsOutbound outbound) {
		super.onOpen(outbound);
		ChatConnectionPool.addConnection(this);
	}
	@Override
	protected void onClose(int status) {
		super.onClose(status);
		ChatConnectionPool.removeConnection(this);
	}
	
	@Override
	protected void onBinaryMessage(ByteBuffer message) throws IOException {
		throw new UnsupportedOperationException("Binary message not supported.");
	}

	protected  void onTextMessage(CharBuffer message){
	    String recievedMessage = message.toString();
	    int privateStringLength= "toAdmin#".length();
	    if(recievedMessage.length() >= privateStringLength && recievedMessage.subSequence(0, privateStringLength).equals("toAdmin#")){
		ChatConnectionPool.broadcastMessage(recievedMessage, Arrays.asList("Klienditeenindaja") , group);	
		recievedMessage = recievedMessage.substring(privateStringLength);
		ChatConnectionPool.broadcastMessage(recievedMessage, Arrays.asList(group) , group);			
	    }else if(recievedMessage.contains("toClient#")){
		String[] parts = recievedMessage.split("#");
		if(parts.length > 2){
		    ChatConnectionPool.broadcastMessage(parts[2], Arrays.asList(parts[1], group), group);
		}
	    }else{
		ChatConnectionPool.broadcastMessage(message.toString(), null, group);
	    }    		
	}

}
